import React, { Component } from 'react';
import styles from './index.module.scss';
import { withRouter } from 'next/router';
import { withTranslation } from 'next-i18next';
import { getMcpserverList, getAppliedList, getPluginsType } from '@/api/plugins';
import { toast } from '@/components/basicComp/Toast';
import { connect } from 'react-redux';
import { update } from '@/utils/immutableUtil';
import { Context } from './context';
import { motion } from 'framer-motion';
import { Search, X, Settings, Plus, Trash2 } from 'lucide-react';
import classNames from 'classnames';
import * as Dialog from '@radix-ui/react-dialog';
import Discover from './Discover';
import Installed from './Installed';
import ConfirmDialog from './Confirm';
import AddPluginModal from './AddPluginModal';
import _ from 'lodash';

@withTranslation('common')
@withRouter
@connect(({ }) => ({}))
class Comp extends Component {
  state = {
    discoverList: [],
    installPluginList: [],
    categories: [],//类型列表
    activeCategory: 'All', //当前类型
    activeTab: 'discover',
    selectCustomPlugin: { newEnv: [], newArgs: [] },//选中的自定义插件
  };

  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);
  constructor(props) {
    super(props);
    this.state = {
      activeTab: 'discover',
      searchQuery: '',
      activeCategory: 'All',
      isAddCustomPluginOpen: false,
      newPluginName: '',
      enableAutomatically: true,
      isJsonMode: false,
      jsonConfig: '',
      isPluginDetailsOpen: false,
      selectedPlugin: null,
      selectCustomPlugin: { newEnv: [], newArgs: [] },// 选中的自定义插件
      pluginDetailsTab: 'about',
      showConfirmDialog: false,
      pluginToDelete: null,
      isLoading: true,
      categories: [],//类型列表
      discoverList: [
        // {
        //   "server_name": "amap-maps",
        //   "server_description": "高德地图mcp",
        //   "server_tag": "aaa",
        //   "applied": true,
        //   "execute_authorization": true,
        //   "env": {
        //     "AMAP_MAPS_API_KEY": ""
        //   },
        //   "args": [
        //     "-y",
        //     "@amap/amap-maps-mcp-server"
        //   ],
        //   "command": "npx"
        // },
        // {
        //   "server_name": "google-search",
        //   "server_description": "谷歌搜索mcp",
        //   "server_tag": "bbb",
        //   "applied": true,
        //   "execute_authorization": true,
        //   "env": {
        //     "GOOGLE_API_KEY": "",
        //     "GOOGLE_SEARCH_ENGINE_ID": ""
        //   },
        //   "args": [
        //     "-y",
        //     "@adenot/mcp-google-search"
        //   ],
        //   "command": "npx"
        // },
        // {
        //   "server_name": "playwright",
        //   "server_description": "playwright 网络检索",
        //   "server_tag": "bbb",
        //   "applied": true,
        //   "execute_authorization": true,
        //   "env": {},
        //   "args": [
        //     "--directory",
        //     "/your-playwright-mcp-server-clone-directory",
        //     "run",
        //     "@modelcontextprotocol/playwright-mcp-server"
        //   ],
        //   "command": "npx"
        // }
      ],
      installPluginList: [],
      pluginModalTitle: '',//modal标题
      pluginModalType: 'install',//modal类型 install | add | view
    };
    // 初始化防抖函数（延迟 300ms）
    this.debouncedSearch = _.debounce(this.debouncedHandleSearchChange, 300);
  }


  componentDidMount = async () => {
    this.init();
  }
  init = async () => {
    const { activeTab } = this.state;
    if (activeTab == 'discover') {
      this.getDiscoverList()
    } else {
      this.getInstallList()
    }
    this.getPluginsType({ tag_type: 'mcp_server_tag' });
  }

  handleTabChange = (tab) => {
    this.setState({ activeTab: tab, searchQuery: '', activeCategory: 'All', });
    if (tab == 'discover') {
      this.getDiscoverList()
    } else {
      this.getInstallList()
    }
  };

  handleCategoryChange = (category) => {
    const { searchQuery } = this.state;
    this.setState({ activeCategory: category });
    this.getDiscoverList({ server_name: searchQuery, server_type: category });
  };
  // 实际处理搜索的防抖方法
  debouncedHandleSearchChange = (e) => {
    const { activeTab } = this.state; // 每次执行时获取最新 state
    const searchValue = e.target.value;
    // 根据当前 tab 发起请求
    if (activeTab === 'discover') {
      this.getDiscoverList({ server_name: searchValue });
    } else {
      this.getInstallList({ server_name: searchValue });
    }
  };

  handleSearchChange = (e) => {
    const searchValue = e.target.value;
    // 立即更新搜索框的本地状态
    this.setState({ searchQuery: searchValue });
    this.debouncedSearch(e);
  };
  // 获取添加插件弹窗中，所有值
  getAddCustomPluginValue = () => {
    const { selectCustomPlugin } = this.state;
    console.log('selectCustomPlugin: ', selectCustomPlugin);
    let newSelectCustomPlugin = { ...selectCustomPlugin }
    const { newEnv, newArgs, ...reqData } = newSelectCustomPlugin;
    let env = {}
    let args = [];
    let shouldContinue = true;

    for (const item of newEnv || []) {
      if (!shouldContinue) break;

      if (!item.key || !item.value) {
        toast.error('请填写Environment Variable');
        shouldContinue = false;
        continue; // 可选：跳过后续逻辑
      }

      env[item.key] = item.value;
    }
    for (const item of newArgs || []) {
      if (!shouldContinue) break;

      if (!item.value) {
        toast.error('请填写Arguments');
        shouldContinue = false;
        continue; // 可选：跳过后续逻辑
      }

      args.push(item.value)
    }
    reqData.env = env;
    reqData.args = args;
    console.log('reqData: ', reqData);

    return { shouldContinue, reqData };
  }
  // 弹窗install插件  添加按钮调用接口
  handleAddCustomPlugin = async () => {
    const { shouldContinue, reqData } = this.getAddCustomPluginValue();
    if (!shouldContinue) {
      return; // 终止后续代码
    }
    var rs = await installPlugin(reqData);
    if (rs.data?.code == 200) {
      const { activeTab } = this.state;
      if (activeTab == 'discover') {
        this.getDiscoverList()
      } else {
        this.getInstallList()
      }
    } else {
      toast.error('添加插件失败');
    }

    this.setState({ isAddCustomPluginOpen: false, selectCustomPlugin: {} });
  };

  //获取弹窗中修改插件的值
  getPluginChangeValue = (params) => {
    const { selectCustomPlugin } = this.state;
    let newSelectCustomPlugin = { ...selectCustomPlugin, ...params }
    this.setState({ selectCustomPlugin: newSelectCustomPlugin })
  }


  handleEnableAutomaticallyChange = () => {
    this.setState(prevState => ({ enableAutomatically: !prevState.enableAutomatically }));
  };

  toggleJsonMode = () => {
    this.setState(prevState => ({ isJsonMode: !prevState.isJsonMode, jsonConfig: '' }));
  };

  handleJsonConfigChange = (e) => {
    this.setState({ jsonConfig: e.target.value });
  };

  openPluginDetails = (plugin) => {
    this.setState({
      isPluginDetailsOpen: true,
      selectedPlugin: plugin,
      pluginDetailsTab: 'about'
    });
  };
  // 打开添加自定义插件 弹窗
  openAddCustomPlugin = (plugin) => {
    this.setState({
      isAddCustomPluginOpen: true,
      selectCustomPlugin: plugin,
      pluginDetailsTab: 'about'
    });
  };

  handlePluginDetailsTabChange = (tab) => {
    this.setState({ pluginDetailsTab: tab });
  };

  handleDeletePlugin = () => {
    console.log('Deleting plugin:', this.state.selectedPlugin?.name);
    this.setState({
      isPluginDetailsOpen: false,
      showConfirmDialog: true,
      pluginToDelete: this.state.selectedPlugin
    });
  };

  confirmDelete = () => {
    console.log('Confirmed deletion of plugin:', this.state.pluginToDelete?.name);
    // Actual deletion logic would go here
    this.setState({ showConfirmDialog: false, pluginToDelete: null });
  };

  cancelDelete = () => {
    this.setState({ showConfirmDialog: false, pluginToDelete: null });
  };

  handleEditPlugin = () => {
    console.log('Editing plugin:', this.state.selectedPlugin?.name);
    // Implementation for editing a plugin
  };

  getPluginIcon = (name) => {
    // Simple function to return an icon based on plugin name
    // In a real implementation, you might use actual icons
    const firstLetter = name.charAt(0).toUpperCase();
    return <div className={styles.pluginIcon}>{firstLetter}</div>;
  };



  // 获取discover列表数据
  getDiscoverList = async (data) => {
    const { activeCategory, searchQuery } = this.state;
    let server_type = data?.server_type ? data?.server_type : activeCategory;
    if (server_type == 'All') {
      server_type = '';
    }
    let reqData = {
      server_name: data?.server_name ? data?.server_name : searchQuery,
      server_type,
    }
    var rs = await getMcpserverList(reqData);
    console.log('rs: ', rs);
    if (rs.data?.code == 200) {
      var data = rs.data.data;
      this.setState({ discoverList: data });
    }
  };

  // 获取install 列表数据
  getInstallList = async (data) => {
    let reqData = {
      server_name: data?.server_name ? data?.server_name : '',
    }
    var rs = await getAppliedList(reqData);
    if (rs.data?.code == 200) {
      var data = rs.data.data;
      this.setState({ installPluginList: data });
    }
  };

  // 获取插件分类
  getPluginsType = async (data) => {
    var rs = await getPluginsType(data);
    if (rs.data?.code == 200) {
      var data = rs.data.data;
      this.setState({ categories: data });
    }
  }



  // 转换json数据
  handleJsonData = () => {
    const { jsonConfig, selectCustomPlugin } = this.state;
    // 转换json数据
    let jsonData = { ...JSON.parse(jsonConfig)?.mcpServers };
    let transformed = {};
    for (const [serverName, config] of Object.entries(jsonData)) {
      console.log('config: ', config);
      transformed = {
        server_name: serverName, // 使用服务器名称作为 server_name
        server_description: `Description for ${serverName}`, // 示例描述（可根据需求修改）
        applied: selectCustomPlugin?.applie, // 默认值
        execute_authorization: selectCustomPlugin?.execute_authorization, // 默认值
        env: config.env || {}, // 保留原始 env
        args: config.args || [], // 保留原始 args
        command: config.command || "", // 保留原始 command
      };
    }

    // this.toggleJsonMode();
    let fromData = this.handleFormData(transformed);
    this.setState({ isJsonMode: false, selectCustomPlugin: fromData });
  }

  // 转换 form可以识别的数据
  handleFormData = (plugin) => {
    let newEnv = Object.keys(plugin?.env).map((item => {
      return { key: item, isRequired: true, value: plugin?.env[item] }
    }))
    let newPlugin = { ...plugin };
    newPlugin.newEnv = newEnv;
    let newArgs = plugin?.args.map(item => {
      return { isRequired: true, value: item }
    })
    newPlugin.newArgs = newArgs;
    newPlugin.isEdit = true;
    return newPlugin;
  }


  getImg = (key) => {
    const { router } = this.props;
    var base = '';
    if (router.basePath) {
      base = router.basePath;
    }
    var map = {
      'amap-maps': `${base}/img/models/azure.png`,
      'google-search': `${base}/img/models/openai.png`,
      tongyi: `${base}/img/models/tongyi.png`,
      deepseek: `${base}/img/models/deepseek.png`,
      anthropic: `${base}/img/models/anthropic.png`,
      default: `${base}/img/models/default.png`,
    };
    let imgUrl = map[key] || map['default']
    return imgUrl;
  };

  componentWillUnmount() {
    // 组件卸载时取消未执行的防抖
    this.debouncedSearch.cancel();
  }

  render() {
    const {
      activeTab,
      searchQuery,
      activeCategory,
      isAddCustomPluginOpen,
      isJsonMode,
      jsonConfig,
      isPluginDetailsOpen,
      selectedPlugin,
      pluginDetailsTab,
      categories,
      discoverList,
      installPluginList,
      selectCustomPlugin,//选中的CustomPlugi 的值
      pluginModalTitle,
      pluginModalType,
    } = this.state;

    return (
      <motion.div
        initial={{ opacity: 0 }} // 初始状态：不透明度为 0
        animate={{ opacity: 1 }} // 动画状态：不透明度为 1
        transition={{ duration: 0.5 }} // 动画持续时间为 1 秒
        style={{ height: '100%' }}
      >
        <Context.Provider value={this.controller}>
          <div className={styles.container}>
            {/* Tabs */}
            <div className={styles.tabs}>
              <div
                className={classNames(styles.tab, {
                  [styles.active]: activeTab === 'discover',
                })}
                onClick={() => this.handleTabChange('discover')}
              >
                Discover Plugins
              </div>
              <div
                className={classNames(styles.tab, {
                  [styles.active]: activeTab === 'installed',
                })}
                onClick={() => this.handleTabChange('installed')}
              >
                Installed Plugins
              </div>
            </div>

            {/* Search Bar */}
            <div className={styles.searchContainer}>
              <Search className={styles.searchIcon} />
              <input
                type="text"
                className={styles.searchInput}
                placeholder="Search plugins..."
                value={searchQuery}
                onChange={this.handleSearchChange}
              />
            </div>

            {/* Categories */}
            {activeTab === 'discover' && <div className={styles.categories}>
              <div
                className={classNames(styles.category, {
                  [styles.active]: activeCategory === 'All',
                })}
                onClick={() => this.handleCategoryChange('All')}
              >

                <span>
                  <i
                    className="iconfont icon-all"
                  ></i><span>{'All'}</span>
                </span>

              </div>
              {categories?.map((category, index) => (
                <div
                  key={category}
                  className={classNames(styles.category, {
                    [styles.active]: activeCategory === category,
                  })}
                  onClick={() => this.handleCategoryChange(category)}
                >
                  <span  >{category}</span>
                </div>
              ))}
            </div>}
            {/* 添加自定义插件 */}

            {activeTab === 'discover' && <div className={styles.addCustomButtonContainer}>
              <button
                className={styles.addCustomButton}
                onClick={() => this.setState({
                  selectCustomPlugin: {
                    isEdit: false, 
                    newEnv: [{ key: '', isRequired: true, value: null }], 
                    newArgs: [],
                    execute_authorization: false,
                    server_tag:categories[0],
                  }, 
                  isAddCustomPluginOpen: true,
                  pluginModalTitle: 'Add Custom Plugin',
                  pluginModalType: 'add'
                })}
              >
                <Plus size={16} />
                Add Custom Plugin
              </button>

            </div>}

            {activeTab === 'discover' && <div className={styles.line}></div>}

            {activeTab === 'discover' && <Discover
              discoverList={discoverList}
              getDiscoverList={this.getDiscoverList}
              openPluginDetails={this.openPluginDetails}
              openAddCustomPlugin={this.openAddCustomPlugin}
              changeModalTitle={(title) => {
                this.setState({ pluginModalTitle: title })
              }}
              getImg={this.getImg}
              changParentState = {(params)=>{
                this.setState(params)
              }}
            />}

            {activeTab === 'installed' && <Installed
              installPluginList={installPluginList}
              getInstallList={this.getInstallList}
              openPluginDetails={this.openPluginDetails}
              openAddCustomPlugin={this.openAddCustomPlugin}
              changeModalTitle={(title) => {
                this.setState({ pluginModalTitle: title })
              }}
              getImg={this.getImg}
            />}

            {/* Add Custom Plugin Modal */}
            <AddPluginModal
              isAddCustomPluginOpen={isAddCustomPluginOpen}
              onOpenChange={(open) => this.setState({ isAddCustomPluginOpen: open })}
              pluginModalTitle={pluginModalTitle}
              selectCustomPlugin={selectCustomPlugin}
              getDiscoverList={this.getDiscoverList}
              getInstallList={this.getInstallList}
              pluginModalType = {pluginModalType}
            />

            {/* Plugin Details Modal */}
            <Dialog.Root
              open={isPluginDetailsOpen}
              onOpenChange={(open) => !open && this.setState({ isPluginDetailsOpen: false })}
            >
              <Dialog.Portal>
                <Dialog.Overlay className={styles.dialogOverlay} />
                <Dialog.Content className={styles.pluginDetailsContent}>
                  <div className={styles.pluginDetailsHeader}>
                    <Dialog.Title className={styles.pluginDetailsTitle}>
                      View {selectedPlugin?.name} Plugin
                    </Dialog.Title>
                    <Dialog.Close asChild>
                      <button className={styles.closeButton}>
                        <X size={18} />
                      </button>
                    </Dialog.Close>
                  </div>

                  <div className={styles.pluginDetailsTabs}>
                    <div
                      className={classNames(styles.pluginDetailsTab, {
                        [styles.active]: pluginDetailsTab === 'about'
                      })}
                      onClick={() => this.handlePluginDetailsTabChange('about')}
                    >
                      About
                    </div>
                    <div
                      className={classNames(styles.pluginDetailsTab, {
                        [styles.active]: pluginDetailsTab === 'tools'
                      })}
                      onClick={() => this.handlePluginDetailsTabChange('tools')}
                    >
                      Tools
                    </div>
                    <div className={styles.viewSourceButton}>
                      View Source
                    </div>
                  </div>

                  <div className={styles.pluginDetailsBody}>
                    {pluginDetailsTab === 'about' ? (
                      <div className={styles.aboutContent}>
                        <p className={styles.pluginDescription}>
                          MCP Server for the GitHub API, enabling file operations, repository management/search functionality, and more.
                        </p>

                        <h3 className={styles.featuresTitle}>Features</h3>
                        <ul className={styles.featuresList}>
                          <li>Automatic Branch Creation: When creating/updating, new or pushing changes,branches are automatically created if they don't exist</li>
                          <li>Comprehensive Error Handling: Clear error messages for common issues</li>
                          <li>Git History Preservation: Operations maintain proper Git history without force pushing</li>
                          <li>Batch Operations: Support for both single-file and multi-file operations</li>
                          <li>Advanced Search: Support for searching code, issues/PRs, and users</li>
                        </ul>
                      </div>
                    ) : (
                      <div className={styles.toolsContent}>
                        <p>Tools content goes here</p>
                      </div>
                    )}
                  </div>

                  <div className={styles.pluginDetailsFooter}>
                    <button
                      className={styles.deletePluginButton}
                      onClick={this.handleDeletePlugin}
                    >
                      Delete Plugin
                    </button>
                    <button
                      className={styles.editPluginButton}
                      onClick={this.handleEditPlugin}
                    >
                      Edit Plugin
                    </button>
                  </div>
                </Dialog.Content>
              </Dialog.Portal>
            </Dialog.Root>

            {/* Confirm Dialog */}
            <ConfirmDialog
              isOpen={this.state.showConfirmDialog}
              title={`Delete ${this.state.pluginToDelete?.name}`}
              message="Are you sure to delete the model? You can continue to configure the model after deletion."
              onCancel={this.cancelDelete}
              onConfirm={this.confirmDelete}
              cancelText="Cancel"
              confirmText="Delete"
            />
          </div>
        </Context.Provider>
      </motion.div>
    );
  }
}

export default Comp;
